import pygame
import sys
import os
import time
import traceback
from random import *
from pygame.locals import *
from psychopy import gui
import pandas as pd
import numpy as np

single_nums = 15    # 单次试验要测试的字数
max_count = 3       # 同一受试者要重复进行的试验次数
# id读取界面
def GetSubject():
    """
    返回被试的id
    """
    myDlg = gui.Dlg(title="请输入学号后四位作为被试ID")
    myDlg.addField(u'被试ID:')
    myDlg.show()
 
    if myDlg.OK:
        thisInfo = myDlg.data
     
    else:
        exit(0)
        
    return thisInfo[0]

# 显示文字方法
def text_show (size,target_text,pos_x,pos_y):
    '''size:字体大小，target_text：显示内容，pos_x,pos_y：显示位置'''
    result_font = pygame.font.SysFont(font,size) # 调用系统字体
    result_text = result_font.render(target_text,True,(0,0,0)) # 创建Surface对象，以绘制文本
    result_rect = result_text.get_rect() #设置位置
    result_rect.center = (pos_x, pos_y)
    screen.blit(result_text, result_rect)


# 规则页
def first_surface():
    running = False
    begin = False
    count = 1
    while not begin:
        
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()
            elif event.type == KEYDOWN:
                running = True
                main(running,count)
                count += 1
            if count > max_count:
                begin = True
            screen.fill((255,255,255))
            text_caption = "STROOP TEST !"
            text_show(96,text_caption,width/2,(height/2-260))

            text_rule1 = "规  则"
            text_show(48,text_rule1,width/2,(height/2-120))
            text_rule2 = "大声读出词汇，并判断词汇的【字体颜色】"
            text_show(28,text_rule2,width/2,(height/2-20))
            text_rule3 = "如果字体为“红色”，则按下【R】键"
            text_show(28,text_rule3,width/2,(height/2+30))
            text_rule4 = "如果字体为“绿色”，则按下【G】键"
            text_show(28,text_rule4,width/2,(height/2+80))
            text_rule5 = "如果字体为“蓝色”，则按下【B】键"
            text_show(28,text_rule5,width/2,(height/2+130))

            id_word = f"id为{id}的受试者的第{count}次试验："
            text_show(16,id_word,width/2,(height/2+240))
            text_begin = "按下 *任意键* 【开始】"
            text_show(16,text_begin,width/2,(height/2+260))
            
            pygame.display.flip() # 刷新页面


#测试程序
def main(running,count):
    words = ['红','绿','蓝']
    # words = {0:['红',[]],1:['绿',[]],2:['蓝',[]]}
    word = choice(words)
    word_ = word
    word_font = pygame.font.SysFont(font,288)
    
    
    events = {'times':[],'corrects':[],'显示文字':[],'显示文字颜色':[],'受试者选项':[]}
    initTime = pygame.time.get_ticks()
    lastTime = pygame.time.get_ticks()
    newTime = pygame.time.get_ticks()
    differTime = 0
    everyTime = 0 #平均时间
    #颜色
    colors = []
    GREEN = (0,255,0)
    colors.append(GREEN)
    RED = (255,0,0)
    colors.append(RED)
    BLUE = (0,0,255)
    colors.append(BLUE)
    color_word = {RED:'红',GREEN:'绿',BLUE:'蓝'}

    color = choice(colors)
    #判断是否正确
    correct = True
    #用于计数
    number = 0
    get = -1
    
    while running:
        get = 0
        for event in pygame.event.get():
            
            if event.type == QUIT:
                sys.exit()
            elif event.type == KEYDOWN:
                if  number <single_nums:
                    
                    if event.key == K_r:
                        newTime = pygame.time.get_ticks()
                        differTime = newTime - lastTime
                        if color == RED:
                            correct = True
                        else:
                            correct = False
                        # events = {'times':[],'corrects':[],'显示文字':[],'显示文字颜色':[],'受试者选项':[]}
                        events['times'].append(differTime)
                        events['corrects'].append(correct)
                        events['显示文字'].append(word)
                        events['显示文字颜色'].append(color_word[color])
                        events['受试者选项'].append('红')
                        number += 1
                        color = choice(colors)
                        get = 1
                        
                        
                    
                    if event.key == K_g:
                        newTime = pygame.time.get_ticks()
                        differTime = newTime - lastTime
                        if color == GREEN:
                            correct = True
                        else:
                            correct = False
                        events['times'].append(differTime)
                        events['corrects'].append(correct)
                        events['显示文字'].append(word)
                        events['显示文字颜色'].append(color_word[color])
                        events['受试者选项'].append('绿')
                        number += 1
                        color = choice(colors)
                        get = 1


                    if event.key == K_b:
                        newTime = pygame.time.get_ticks()
                        differTime = newTime - lastTime
                        if color == BLUE:
                            correct = True
                        else:
                            correct = False
                        events['times'].append(differTime)
                        events['corrects'].append(correct)
                        events['显示文字'].append(word)
                        events['显示文字颜色'].append(color_word[color])
                        events['受试者选项'].append('蓝')
                        number += 1
                        color = choice(colors)
                        get = 1
        # 画白色背景
        screen.fill((255,255,255))
        lastTime = newTime
        if number < single_nums:
            if get != 0 and correct :
                while word == word_:
                    word = choice(words)
                word_ = word
            word_text = word_font.render(word, True, color)
            wordRect = word_text.get_rect()
            wordRect.center = (width/2,height/2)
            screen.blit(word_text, wordRect)
            
        elif number == single_nums:
            save_record(id,count,events)
            number += 1
            everyTime = (newTime - initTime)/20
        else:
            count_num = 0
            for i in events['corrects']:
                if i == False:
                    count_num += 1
            resultText = "平均用时为：" + str(everyTime) + "毫秒，犯错个数为：" + str(count_num) + "个" 
            text_show(54,resultText,width/2,height/2)
            pygame.display.flip()
            time.sleep(1)
            running = False
        pygame.display.flip()

# 将结果保存为csv文件
def save_record(id,count,events):
    data = pd.DataFrame(events)
    data['id'] = id
    data['实验序号'] = count
    save_path = 'File\\record_data.csv'
    if os.path.exists(save_path):
        data_before = pd.read_csv(save_path)
        data_all = pd.concat([data_before,data],ignore_index=True)
        data_all.to_csv(save_path,encoding="utf_8_sig",index=False)
    else:
        data.to_csv(save_path,encoding="utf_8_sig",index=False)
     



if __name__ == '__main__':
    try:
        font = u'华文宋体'
        
        id = GetSubject()
        pygame.init()
        bg_size = width, height = 1280, 720
        screen = pygame.display.set_mode(bg_size)
        pygame.display.set_caption('Stroop Test')

        first_surface()
    except SystemExit:
        pass
    except:
        traceback.print_exc()
        pygame.quit()